package com.chongba.schedule;

import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: admin
 * @time: 2022/12/1 15:03
 */
public class TimerTaskTest2 {
    public static void main(String[] args) {
        //Timer运行多个TimeTask时，只要其中之一没有捕获抛出的异常，其它任务便会自动终止运行
        /*Timer timer = new Timer();

        for (int i = 0; i < 100; i++) {
            int finalI = i;
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println(finalI);
                    if(finalI == 20){
                        throw new RuntimeException();
                    }
                }
            }, 1000L);
        }*/

        //优化Timer多线程相互影响的问题
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            scheduledExecutorService.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println(finalI);
                    if(finalI == 20){
                        throw new RuntimeException();
                    }
                }
            }, 1, TimeUnit.SECONDS);
        }




    }


}
